var MerchantModel = require('../models').Merchant;
const _ = require('lodash');

module.exports = {
    addMerchant : addMerchant,
    check:check,
    updateMerchant:updateMerchant,
    updateBlockState: updateBlockState,
    updateRealInfo: updateRealInfo
}

function updateBlockState(mid,block,state,callback) {

    // if(_.isEmpty(block) || _.isEmpty(mid)||_.isEmpty(state)){
    //     callback(new Error("mid or block is empty."), null);
    // }else{
        MerchantModel.update({"_id": mid}, {$set: {'block':block,'state':state}}, function(err, docs){
            console.log(docs);
            if(docs == null){
                callback(err, null);
            }else{
                callback(err, docs);
            }
        });
    // }
}

function updateRealInfo(mid,block,state,msg,callback) {

    // if(_.isEmpty(block) || _.isEmpty(mid)||_.isEmpty(state)){
    //     callback(new Error("mid or block is empty."), null);
    // }else{
    MerchantModel.update({"_id": mid}, {$set: {'block':block,'state':state,'msg':msg}}, function(err, docs){
        console.log(docs);
        if(docs == null){
            callback(err, null);
        }else{
            callback(err, docs);
        }
    });
    // }
}

function addMerchant(merchant,callback) {
    var mer = new MerchantModel(merchant);
    mer.save(callback);
    // MerchantModel.findOne({'name': merchant.name}, callback);
}

function updateMerchant(newMerchant,callback) {
    // storeName
    MerchantModel.update({'_id': newMerchant._id}, {
        'storeName': newMerchant.storeName, 'address': newMerchant.address
    }, function (err, doc) {
        console.log(doc);
        if (err) {
            callback(err);
        }
        else {
            MerchantModel.findOne({'_id': newMerchant._id},callback);
        }
    });
}


function check(name,password,callback) {

    MerchantModel.findOne({name: name,password:password}, callback);
}

